import { createWebHashHistory, createRouter } from 'vue-router'
import { storeToRefs } from 'pinia';
import { useUserStore } from '../store/user';

const routes = [
  { name: 'home',
    path: '/', 
    component: () => import ('../views/Home.vue') 
  },
  { name: 'login',
    path: '/login', 
    component: () => import ('../views/Login.vue') 
  },
  { name: 'settings',
    path: '/settings', 
    component: () => import ('../views/Settings.vue'),
    meta: { requiresAuth: true }
   },
    
  { name: 'editor',
    path: '/editor', 
    component: () => import ('../views/EditArticle.vue'),
    meta: { requiresAuth: true }
  },
  { name: 'update_article',
    path: '/editor/:slug', 
    component: () => import ('../views/EditArticle.vue'),
    meta: { requiresAuth: true }
  },
  { name: 'register',
    path: '/register', 
    component: () => import ('../views/Register.vue') 
  },
  { name: 'profile',
    path: '/profile/:username', 
    component: () => import ('../views/Profile.vue') 
  },
  { name: 'article',
    path: '/article/:slug', 
    component: () => import ('../views/Article.vue') 
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})
router.beforeEach((to) => {
  let store = useUserStore();
  const { userinfo } = storeToRefs(store);
  if(to.meta.requiresAuth === true && userinfo.value === null){
    return '/login';
  }
})

export default router;